package com.ihemou.common.security.service;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.ihemou.common.core.constant.CacheConstants;
import com.ihemou.common.core.constant.Constants;
import com.ihemou.common.core.utils.ServletUtils;
import com.ihemou.common.core.utils.StringUtils;
import com.ihemou.common.core.utils.ip.IpUtils;
import com.ihemou.system.dto.UserInfo;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Component
public class TokenService {

    private final static long EXPIRE_TIME = Constants.TOKEN_EXPIRE * 60;

    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;

    protected static final long MILLIS_SECOND = 1000;


    /**
     * 创建令牌
     */
    public Map<String, Object> createToken(UserInfo userInfo) {

        // 获取登录token
        StpUtil.login(userInfo.getSysUser().getId());
        // 兼容标准的Oath2属性
        SaTokenInfo saTokenInfo = StpUtil.getTokenInfo();
        // 生成token
//        String token = IdUtils.fastUUID();
        String token = saTokenInfo.tokenValue;
        userInfo.setToken(token);
        userInfo.setUserId(userInfo.getSysUser().getId());
        userInfo.setUsername(userInfo.getSysUser().getUserName());
        userInfo.setIpAddr(IpUtils.getIpAddr(ServletUtils.getRequest()));
        refreshToken(userInfo);

        // 保存或更新用户token
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("access_token", token);
        map.put("expires_in", saTokenInfo.tokenActivityTimeout);
        map.put("userToken", saTokenInfo);
        map.put("userInfo", userInfo);

        SaSession saSession = StpUtil.getTokenSession();
        saSession.set(Constants.USER_INFO_SESSION, JSON.toJSONString(userInfo));
        saSession.set(CacheConstants.DETAILS_USERNAME, userInfo.getUsername());
        saSession.set(CacheConstants.DETAILS_USER_ID, userInfo.getUserId());

        return map;
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public UserInfo getLoginUser() {
        return getLoginUser(ServletUtils.getRequest());
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public UserInfo getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
//        String token = SecurityUtils.getToken(request);
//        if (StringUtils.isNotEmpty(token))
//        {
//            String userKey = getTokenKey(token);
//            UserInfo user = redisService.getCacheObject(userKey);
//            return user;
//        }
        SaSession saSession = StpUtil.getTokenSession();
        String s = saSession.getString(Constants.USER_INFO_SESSION);
        UserInfo userInfo = JSON.parseObject(s, UserInfo.class);

        return userInfo;
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(UserInfo userInfo) {
        if (StringUtils.isNotNull(userInfo) && StringUtils.isNotEmpty(userInfo.getToken())) {
            refreshToken(userInfo);
        }
    }

    public void delLoginUser(String token) {
//        if (StringUtils.isNotEmpty(token))
//        {
//            String userKey = getTokenKey(token);
//            redisService.deleteObject(userKey);
//        }
        StpUtil.checkLogin();
        StpUtil.logout();
    }

    /**
     * 刷新令牌有效期
     *
     * @param userInfo 登录信息
     */
    public void refreshToken(UserInfo userInfo) {
//        userInfo.setLoginTime(System.currentTimeMillis());
//        userInfo.setExpireTime(userInfo.getLoginTime() + EXPIRE_TIME * MILLIS_SECOND);
//        // 根据uuid将loginUser缓存
//        String userKey = getTokenKey(userInfo.getToken());
//        redisService.setCacheObject(userKey, userInfo, EXPIRE_TIME, TimeUnit.SECONDS);
        // 先检查是否已过期
        StpUtil.checkActivityTimeout();
        // 检查通过后继续续签
        StpUtil.updateLastActivityToNow();
    }

    private String getTokenKey(String token) {
        return ACCESS_TOKEN + token;
    }
}
